import {
  ProFormDateMonthRangePicker,
  ProFormDateRangePicker,
  ProFormDateYearRangePicker,
  ProFormInstance,
  ProFormTreeSelect,
  QueryFilter,
} from '@/components/Pro/';
import { parseArray } from '@/pages/Statistics/Battery/utils';
import { TreeNode } from '@/pages/Statistics/ElectricityConsumption/help';
import { statisticEfficiencyControllerGetDateEfficiency as getData } from '@/services/ess/statisticEfficiency';
import { useIntl, useModel } from '@umijs/max';
import { DatePickerProps, message, Spin } from 'antd';
import ReactEcharts from 'echarts-for-react';
import _ from 'lodash';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';

const TableList: React.FC<{
  dateType: number;
  deviceInfo: API.DeviceInfo[];
}> = ({ dateType, deviceInfo }) => {
  const intl = useIntl();
  const { initialState } = useModel('@@initialState');
  const formRef = useRef<ProFormInstance>();
  const chartRef = useRef();
  const [pageData, setPageData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [type, setType] = useState('1');
  const [isEmpty, setEmpty] = useState(true);
  const selectedType = useRef(null);
  const treeData = useRef(deviceInfo);
  const [deviceVal, setDeviceVal] = useState();
  /**
   * 获得禁用列表
   * @param Nodes
   */
  const setDisabled = (Nodes: TreeNode[]): TreeNode[] => {
    return Nodes.map((node) => {
      const newNode: TreeNode = {
        ...node,
        disabled: selectedType.current === null ? false : node.nodeType !== selectedType.current,
      };
      if (newNode.subDevices) {
        newNode.subDevices = setDisabled(newNode.subDevices);
      }
      return newNode;
    });
  };
  useEffect(() => {
    chartRef?.current?.getEchartsInstance()?.resize();
  }, []);

  useEffect(() => {
    formRef?.current?.submit();
  }, [dateType]);
  useEffect(() => {
    if (deviceInfo.length) {
      selectedType.current = 'ROOT';
      setDeviceVal(deviceInfo[0].uniqueId);
      treeData.current = setDisabled([deviceInfo[0]]);
    }
  }, [deviceInfo]);
  const disabledDate: DatePickerProps['disabledDate'] = (current, { from }) => {
    const disabled = current && current >= moment().endOf('day');

    if (from) {
      if (dateType === 1) return disabled || Math.abs(current.diff(from, 'day')) >= 180;
      if (dateType === 2) return disabled || Math.abs(current.diff(from, 'month')) >= 36;
      if (dateType === 3) return disabled || Math.abs(current.diff(from, 'years')) >= 10;
    }

    return disabled;
  };

  const initialValue = () => {
    if (dateType === 1) return [moment().subtract(32, 'days'), moment().subtract(1, 'days')];
    if (dateType === 2) return [moment().subtract(12, 'months'), moment().subtract(1, 'months')];
    if (dateType === 3) return [moment().subtract(5, 'years'), moment().subtract(1, 'years')];
  };
  const getSeriesData = (pageData: any) => {
    const getData = (pageData || []).map((item) => {
      return [
        {
          name: item.locationName
            ? item.locationName + '_' + intl.formatMessage({ id: 'statistics.analyze.chargeTrans' })
            : intl.formatMessage({ id: 'statistics.analyze.chargeTrans' }),
          type: 'line',
          data: item?.charge || [],
          smooth: false,
          //symbol: 'none',
          itemStyle: {
            normal: {
              color: '#FFD50C', //改变折线点的颜色
              lineStyle: {
                color: '#FFD50C', //改变折线颜色
              },
            },
          },
        },
        {
          name: item.locationName
            ? item.locationName + '_' + intl.formatMessage({ id: 'statistics.analyze.netTrans' })
            : intl.formatMessage({ id: 'statistics.analyze.netTrans' }),
          type: 'line',
          data: item?.pocGrid || [],
          smooth: false,
          //symbol: 'none',
          itemStyle: {
            normal: {
              color: '#FF7A0C', //改变折线点的颜色
              lineStyle: {
                color: '#FF7A0C', //改变折线颜色
              },
            },
          },
        },
      ];
    });
    return _.flatten(getData);
  };
  return (
    <div>
      <QueryFilter
        split
        params={{
          deviceVal: deviceVal,
        }}
        formRef={formRef}
        onFinish={async (value) => {
          setLoading(true);
          if (Array.isArray(deviceVal)) {
            if (deviceVal?.length) {
              const ans = parseArray(deviceVal);
              if (ans.nodeType.length) {
                value.areaFlag = ans.nodeType.some((item: string) => {
                  return item === 'AREA';
                });
              }
              value.code = ans.id.join(',');
            } else {
              message.warning(intl.formatMessage({ id: 'statistics.analyze.objWarning' }));
              value.areaFlag = false;
              setLoading(false);
              return false;
            }
          } else {
            value.code = initialState?.stationCode;
            value.areaFlag = false;
            setLoading(false);
          }
          const dateFormat =
            (dateType === 2 && 'YYYY-MM') || (dateType === 3 && 'YYYY') || 'YYYY-MM-DD';
          value.startDate = moment(value.date[0]).format(dateFormat);
          value.endDate = moment(value.date[1]).format(dateFormat);
          delete value.date;
          value.dateType = (dateType === 1 && 'day') || (dateType === 2 && 'month') || 'year';
          value.dataType = type;
          try {
            const res = await getData(value);
            setLoading(false);
            if (res?.success) {
              setPageData(res?.data || []);
              setEmpty(!(res?.data?.length > 0));
              chartRef?.current?.getEchartsInstance()?.clear();
            }
          } catch (e) {
            setLoading(false);
            chartRef?.current?.getEchartsInstance()?.clear();
            setPageData([]);
          }
        }}
        onReset={() => {
          selectedType.current = 'ROOT';
          treeData.current = setDisabled([treeData?.current[0]]);
          setDeviceVal(deviceInfo[0].uniqueId);
          formRef?.current?.submit();
        }}
      >
        {dateType === 1 && (
          <ProFormDateRangePicker
            name="date"
            label={intl.formatMessage({ id: 'statistics.income.select' })}
            initialValue={initialValue()}
            fieldProps={{
              disabledDate: disabledDate,
              allowClear: false,
            }}
          />
        )}
        {dateType === 2 && (
          <ProFormDateMonthRangePicker
            name="date"
            label={intl.formatMessage({ id: 'statistics.income.select' })}
            initialValue={initialValue()}
            fieldProps={{
              disabledDate: disabledDate,
              allowClear: false,
            }}
          />
        )}
        {dateType === 3 && (
          <ProFormDateYearRangePicker
            name="date"
            label={intl.formatMessage({ id: 'statistics.income.select' })}
            initialValue={initialValue()}
            fieldProps={{
              disabledDate: disabledDate,
              allowClear: false,
            }}
          />
        )}
        {/*<ProFormSelect*/}
        {/*  name="dataType"*/}
        {/*  label={intl.formatMessage({ id: 'statistics.work.dimensions' })}*/}
        {/*  initialValue={'1'}*/}
        {/*  valueEnum={{*/}
        {/*    1: {*/}
        {/*      text: intl.formatMessage({ id: 'statistics.work.station' }),*/}
        {/*    },*/}
        {/*    2: {*/}
        {/*      text: intl.formatMessage({ id: 'batteryVoltage.safe.stack' }),*/}
        {/*    },*/}
        {/*  }}*/}
        {/*  onChange={(v) => {*/}
        {/*    setType(v);*/}
        {/*  }}*/}
        {/*  allowClear={false}*/}
        {/*/>*/}
        <ProFormTreeSelect
          name="code"
          label={intl.formatMessage({ id: 'statistics.work.dimensions' })}
          initialValue={deviceVal}
          fieldProps={{
            allowClear: false,
            value: deviceVal,
            treeData: treeData?.current,
            multiple: true,
            maxTagCount: 1,
            maxCount: 100,
            fieldNames: {
              label: 'deviceName',
              value: 'uniqueId',
              children: 'subDevices',
            },
            onSelect: (...args) => {
              let selectOptions = args[1];
              if (selectedType.current === null && selectOptions?.nodeType) {
                selectedType.current = selectOptions?.nodeType;
              }
              treeData.current = setDisabled([treeData?.current[0]]);
            },
            onChange: (...args) => {
              setDeviceVal(args[0]);
              let selectedOptions = args[1];
              if (!selectedOptions.length) {
                //清除后不再做相应限制
                selectedType.current = null;
                treeData.current = setDisabled([treeData?.current[0]]);
              }
              let hasAreaNode: boolean = false;
              let hasStationNode: boolean = false;
              const ans = parseArray(args[0]);
              if (ans.nodeType.length) {
                hasAreaNode = ans.nodeType.some((item: string) => {
                  return item === 'AREA';
                });
                hasStationNode = ans.nodeType.some((item: string) => {
                  return item === 'ROOT';
                });
              }
              setType(hasAreaNode ? '3' : hasStationNode ? '1' : '2');
            },
          }}
        />
      </QueryFilter>
      <Spin spinning={loading}>
        <ReactEcharts
          ref={chartRef}
          style={{ height: 400, marginTop: 20 }}
          option={{
            tooltip: {
              trigger: 'axis',
              // axisPointer: {
              //   type: 'shadow',
              // },
              show: !isEmpty,
              formatter: function (params) {
                let text = `<div>
                ${params[0].axisValueLabel}<br/>`;
                (params || []).forEach((item) => {
                  text += `${item.marker}${item.seriesName}&nbsp;:&nbsp;&nbsp;${item.value ?? ''}`;
                  if (item.value || item.value === 0) {
                    text += '%<br/>';
                  } else {
                    text += '<br/>';
                  }
                });
                text += '</div>';
                return text;
              },
            },
            dataZoom: {
              type: 'inside',
            },
            legend: {
              top: 0,
              right: 0,
              icon: 'item',
            },
            grid: {
              left: 40,
              right: 5,
              top: 40,
              bottom: 15,
              containLabel: true,
              show: true,
              borderColor: 'transparent',
              backgroundColor: isEmpty ? 'transparent' : '#F8F9FA',
            },
            xAxis: [
              {
                type: 'category',
                name: false,
                nameTextStyle: {
                  //y轴上方单位的颜色
                  color: '#222',
                },
                data: pageData[0]?.xdata || [],
                axisTick: {
                  alignWithLabel: true,
                  show: true,
                  inside: true, //刻度内置
                },
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: '#ddd',
                  },
                },
                axisLabel: {
                  color: '#222',
                },
              },
            ],
            yAxis: [
              {
                type: 'value',
                name: intl.formatMessage({ id: 'statistics.common.unitPercent' }),
                nameTextStyle: {
                  //y轴上方单位的颜色
                  color: '#222',
                  align: 'left',
                },
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: '#ddd',
                  },
                },
                axisTick: {
                  show: true,
                  inside: true,
                },
                splitLine: {
                  show: !isEmpty,
                  lineStyle: {
                    type: 'dashed',
                  },
                },
                axisLabel: {
                  color: '#222',
                },
              },
            ],
            series: getSeriesData(pageData),
            // searchFormValue?.dataType === '2'
            //   ? [
            //       {
            //         name: intl.formatMessage({ id: 'statistics.analyze.chargeTrans' }),
            //         type: 'line',
            //         data: pageData?.charge || [],
            //         smooth: false,
            //         //symbol: 'none',
            //         itemStyle: {
            //           normal: {
            //             color: '#FFD50C', //改变折线点的颜色
            //             lineStyle: {
            //               color: '#FFD50C', //改变折线颜色
            //             },
            //           },
            //         },
            //       },
            //     ]
            //   : [
            //       {
            //         name: intl.formatMessage({ id: 'statistics.analyze.chargeTrans' }),
            //         type: 'line',
            //         data: pageData?.charge || [],
            //         smooth: false,
            //         //symbol: 'none',
            //         itemStyle: {
            //           normal: {
            //             color: '#FFD50C', //改变折线点的颜色
            //             lineStyle: {
            //               color: '#FFD50C', //改变折线颜色
            //             },
            //           },
            //         },
            //       },
            //       {
            //         name: intl.formatMessage({ id: 'statistics.analyze.chargeTrans' }),
            //         type: 'line',
            //         data: pageData?.pocGrid || [],
            //         smooth: false,
            //         //symbol: 'none',
            //         itemStyle: {
            //           normal: {
            //             color: '#FF7A0C', //改变折线点的颜色
            //             lineStyle: {
            //               color: '#FF7A0C', //改变折线颜色
            //             },
            //           },
            //         },
            //       },
            //     ],
            graphic: [
              {
                type: 'image',
                silent: true,
                style: {
                  image: require('@/assets/img/empty.png'),
                  width: 180,
                  height: 120,
                },
                bounding: 'raw',
                top: 'center',
                left: 'center',
                invisible: !isEmpty,
              },
              {
                type: 'text', // 类型：文本
                left: 'center',
                top: 260,
                silent: true, // 不响应事件
                invisible: !isEmpty, // 有数据就隐藏
                style: {
                  fill: '#222',
                  text: intl.formatMessage({ id: 'global.noDataYet' }),
                  fontFamily: 'Microsoft YaHei',
                  fontSize: '14px',
                },
              },
            ],
          }}
        />
      </Spin>
    </div>
  );
};
export default TableList;
